import execjs
import requests
import json
import time

'''
传入URL地址，能过Request post请求获取返回的JSON数据。
url：网站地址
method：方法，post或get
param：传递的参数
'''
def get_data(url, method, param):
    # 定义header 信息
    header = {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.63 Safari/537.36",
        "accept": "application/json; charset=utf-8",
        "host": "www.techlabplt.com:8080",
        "Origin": "http://www.techlabplt.com:8080"
    }
    if method == 'post':
        # 发起request post请求
        response = requests.post(url, headers=header, json=param)
    if method == 'get':
        # 发起request post请求
        response = requests.get(url, headers=header)

    # 如果正常返回，遍历输出数据到控制台。
    if response.status_code == 200:
        # 通过返回的数据转换为json格式，或者直接获取response.json。
        jsonData = json.loads(response.text)
        # 返回获取得到的数据
        return jsonData

'''
根据传递过来的网址，获取response数据返回
url：网站地址
'''
def get_response(url):
    # 发送请求
    headers = {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.63 Safari/537.36"
    }
    response = requests.get(url=url, headers=headers)
    return response

'''
传入JavaScript路径，获取JavaScript文件内容。
jsFile：JavaScript文件路径和名称
'''
def get_js(jsFile):
    with open(jsFile, 'r', encoding='utf-8') as f:
        data = f.read()
        return data
'''
根据传递过来的title, play_url来保存数据
title：文件名
play_url：音乐文件所在的URL
'''
def save(title, play_url):
    # 获取音乐文件
    music_content = get_response(play_url).content
    # 保存文件
    with open('D:\\musicDir\\' + title + '.mp3', mode='wb') as f:
        f.write(music_content)
        print(title, '保存成功')

'''
执行主程序
'''
def main(html_url):
    # 1.获取音乐数据
    param = {'type': '1'}
    musicData = get_data(html_url, "post", param)
    # 2.循环遍历音乐数据获取key值
    for i in range(len(musicData)):
        strKey = musicData[i]['key']
        strMusicName = musicData[i]['musicName']
        print(strKey)
        # 3. 通过execjs.compile()编译并加载JavaScript文件内容
        execObj = execjs.compile(get_js('music.js'))
        # 4.使用call调用JavaScript内的minus方法,获取得到hash
        strHash = execObj.call("d", strKey)
        print(strHash)
        # 5.获取音乐下载的地址
        param = {}
        url = 'http://www.techlabplt.com:8080/BD-PC/playMusic?m=play&hash=' + strHash
        musicUrl = get_data(url, 'get', param)['playURL']
        print(musicUrl)
        # 6.保存音乐文件
        save(strMusicName, musicUrl)
        # 7.等待1秒
        time.sleep(1)
if __name__ == '__main__':
    url = "http://www.techlabplt.com:8080/BD-PC/music/selectMusicByType"
    main(url)
